package com.palfund.tablayoutviewpagerfragment;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private TabLayout mTabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
        final ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
        String[] titles = getResources().getStringArray(R.array.title);
        ArrayList<BlankFragment> list = new ArrayList<>();
        for (int i = 0; i < titles.length; i++) {
            BlankFragment fragment = BlankFragment.newInstance(i);
            list.add(fragment);
        }
        BlankFragmentPagerAdapter adapter = new BlankFragmentPagerAdapter
                (getSupportFragmentManager(), list, titles);
        viewPager.setAdapter(adapter);
        // ViewPager有一个预加载的特性.默认情况下,预先加载一个Fragment.
        // 默认加载1页.设置0,无效!
        viewPager.setOffscreenPageLimit(1);
        int width = getResources().getDisplayMetrics().widthPixels / titles.length;
        Log.i("MainActivity", "---onCreate()--->width" + width);
        //        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width,
        // ViewGroup
        //                .LayoutParams.MATCH_PARENT);
        //        for (int i = 0; i < titles.length; i++) {
        //            View view = LayoutInflater.from(this).inflate(R.layout.tab, null);
        //            ImageView iv_tab = (ImageView) view.findViewById(R.id.iv_tab);
        //            iv_tab.setImageResource(R.mipmap.ic_launcher);
        //            TextView tv_tab = (TextView) view.findViewById(R.id.tv_tab);
        //            tv_tab.setText(titles[i]);
        //            TabLayout.Tab tab = tabLayout.newTab();
        //            //view.setLayoutParams(layoutParams);
        //            tab.setCustomView(view);
        //            tabLayout.addTab(tab, i);
        //        }
        // 先清除所有tab
        mTabLayout.setupWithViewPager(viewPager);
        resetIndicatorwidth(mTabLayout, 0, 0, 60);
        // 设置scrollable指示器宽度
        //setTabLayoutIndicatorWidth(mTabLayout,  0, 0, 60);
        // 选择的tab和当前显示的tab不相临时,避免出现闪屏
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition(), false);
                Log.i("MainActivity", "---onTabSelected()--->" + tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        // 设置fixed指示器宽度
        //resetIndicatorwidth(mTabLayout, 0, 0, 0);
    }

    /**
     * @param tabLayout
     * @param leftDip   tab间的左边距
     * @param rightDip  tab间的右边距
     * @param plusWidth 比字体宽
     */
    public void setTabLayoutIndicatorWidth(TabLayout tabLayout, int leftDip, int rightDip, int
            plusWidth) {
        //拿到tabLayout的mTabStrip属性
        Field mTabStripField = null;
        try {
            mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
            mTabStripField.setAccessible(true);
            LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);
            int left = dp2px(leftDip);
            int right = dp2px(rightDip);
            int plus = dp2px(plusWidth);
            for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                View tabView = mTabStrip.getChildAt(i);
                //拿到tabView的mTextView属性
                Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                mTextViewField.setAccessible(true);
                TextView mTextView = (TextView) mTextViewField.get(tabView);
                tabView.setPadding(0, 0, 0, 0);
                //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                int width = mTextView.getWidth();
                if (width == 0) {
                    mTextView.measure(0, 0);
                    width = mTextView.getMeasuredWidth();
                }
                //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView
                        .getLayoutParams();

                params.width = width + plus;
                params.leftMargin = left;
                params.rightMargin = right;
                tabView.setLayoutParams(params);
                tabView.invalidate();
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    //TabLayout Fixed 的Mode  并且宽度包裹内容
    public void resetIndicatorwidth(TabLayout tabs, int leftDip, int rightDip, int plusWidth) {
        Class<?> tabLayout = tabs.getClass();
        Field mTabStripField = null;
        try {
            mTabStripField = tabLayout.getDeclaredField("mTabStrip");
            mTabStripField.setAccessible(true);
            LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabs);
            int left = dp2px(leftDip);
            int right = dp2px(rightDip);
            int plus = dp2px(plusWidth);
            for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                View tabView = mTabStrip.getChildAt(i);
                tabView.setPadding(0, 0, 0, 0);
                //拿到tabView的mTextView属性
                Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                mTextViewField.setAccessible(true);
                TextView mTextView = (TextView) mTextViewField.get(tabView);
                tabView.setPadding(0, 0, 0, 0);
                //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                int width = mTextView.getWidth();
                if (width == 0) {
                    mTextView.measure(0, 0);
                    width = mTextView.getMeasuredWidth();
                }
                //尽量少用int plus = (int) (getResources().getDisplayMetrics().density) * plusWidth;
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView
                        .getLayoutParams();
                int tabMode = tabs.getTabMode();
                //实现字多宽tab多宽
                if (tabMode == TabLayout.MODE_FIXED) {
                    //必须设置否则不包裹
                    params.weight = 0;
                    //包裹内容否则字数太多分行
                    params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
                } else {
                    params.width = width + plus;
                }
                params.leftMargin = left;
                params.rightMargin = right;
                tabView.setLayoutParams(params);
                tabView.invalidate();
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private int dp2px(int leftDip) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources
                .getSystem().getDisplayMetrics());
    }
}
